/** 
* @Title: CallableAndFuture.java 
* @Package com.lh.threadtest.t9 
* @Description: TODO
* @author Liu 
* @date 2018年1月17日 下午3:28:19 
* @version V1.0 
*/
package com.lh.threadtest.t9;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/** 
* @ClassName: CallableAndFuture 
* @Description: Callable与Future的应用
* 
* 将多个有返回值的任务交给线程池，并等待线程池执行完毕返回结果(谁先完成返回谁)...
* 
* @author Liu
* @date 2018年1月17日 下午3:28:19 
*  
*/
public class CallableAndFuture2 {

	/***
	* @Title: main 
	* @Description: TODO
	* @param @param args
	* @return void
	* @throws 
	*/
	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
		
		for(int i = 1; i <= 10; i++){
			final int seq = i;
			completionService.submit(new Callable<Integer>() {
				
				@Override
				public Integer call() throws Exception {
					TimeUnit.SECONDS.sleep(new Random().nextInt(5));
					return seq;
				}
			});
		}
		
		System.out.println("waiting...");
		
		for(int i = 1; i <= 10; i++){
			try {
				System.out.println(completionService.take().get());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
